﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileStreamProj
{

  
    public partial class Form1 : Form
    {

      public   string filepath = "";
      public int port = 8899;
      public Boolean Flag = true;
      public   byte[] byData = new byte[906];
      public FileStream aFile;
       public  Thread myThread;
       public  IPEndPoint iep =null;
       public TcpListener tcpListener = null;
       public TcpClient tcpClient = null;
       public NetworkStream stream = null;
       public IPAddress IPA = null;
        public Form1()
        {
            InitializeComponent();
            init();
        }

        private void init()
        {
            IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
           // IPHostEntry ipe = Dns.GetHostEntry();
            int i = 0;
            while (true)
            { 
                
                if (ipe.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                {
                    IPA = ipe.AddressList[i];
                    TXIP.Text = IPA.ToString();
                    break;
                }
                i++;
            }
           
        }

        /// <summary> /// 发送数据到远程主机 /// </summary>
        //private void sendData()
        //{
        //    UdpClient udpClient = new UdpClient();
        //    IPAddress remoteIP;
        //    if (IPAddress.TryParse(TXIP.Text, out remoteIP) == false)
        //    {
        //        MessageBox.Show("远程IP格式不正确"); return;
        //    }
        //    IPEndPoint iep = new IPEndPoint(remoteIP, port);
        //    aFile = new FileStream(filepath, FileMode.Open);
        //    while (Flag)
        //    {
        //        try
        //        {

        //            //E:\睡眠算法\手机数据\数据\原始dat文件.bin
        //            //  FileStream aFile = new FileStream(@"E:\睡眠算法\手机数据\数据\原始dat文件.bin", FileMode.Open);
        //            aFile.Seek(0, SeekOrigin.Current);
        //            aFile.Read(byData, 0, 906);

        //            byte a = byData[0];
        //            //     UdpClient udpClient = new UdpClient("remoteHost", 51666);

        //            // byte[] sendByte = System.Text.Encoding.Unicode.GetBytes("你好!");
        //            udpClient.Send(byData, byData.Length, iep);
        //            Thread.Sleep(250);

        //            //     Console.ReadKey();
        //        }
        //        catch (IOException e)
        //        {
        //            MessageBox.Show(e.Message, "发送失败");
        //        }
        //        finally
        //        {  }
        //    }
        //}

        //tcp发送端
        private void sendData()
        {
            UdpClient udpClient = new UdpClient();
           
            NetworkStream stream = tcpClient.GetStream();
            Flag = true;
          
            aFile = new FileStream(filepath, FileMode.Open);
            while (Flag)
            {
                try
                {

                    //E:\睡眠算法\手机数据\数据\原始dat文件.bin
                    //  FileStream aFile = new FileStream(@"E:\睡眠算法\手机数据\数据\原始dat文件.bin", FileMode.Open);
                    aFile.Seek(0, SeekOrigin.Current);
                    aFile.Read(byData, 0, 906);

                    byte a = byData[0];
                    //     UdpClient udpClient = new UdpClient("remoteHost", 51666);

                    // byte[] sendByte = System.Text.Encoding.Unicode.GetBytes("你好!");
                  //  udpClient.Send(byData, byData.Length, iep);
                    stream.Write(byData, 0, byData.Length);
                    Thread.Sleep(250);

                    //     Console.ReadKey();
                }
                catch (IOException e)
                {
                    MessageBox.Show(e.Message, "发送失败");
                    
                   
                }
                finally
                {
                 //   tcpListener.Stop();
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
    
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
           // MessageBox.Show("我靠");
            openFileDialog1.InitialDirectory = @"C:\Users\a1\Desktop\肖蒙数据.dat";
            //C:\Users\a1\Desktop\肖蒙数据 2014-12-26_15-06-22.dat
            openFileDialog1.Filter = "txt files (*.dat|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filepath = openFileDialog1.FileName;
                TXfilePath.Text = filepath;

                //try
                //{
                //    if ((myStream = openFileDialog1.OpenFile()) != null)
                //    {
                //        using (myStream)
                //        {
                //            // Insert code to read the stream here.
                //        }
                //    }
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                //}
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (tcpClient!=null)
            {
                myThread = new Thread(new ThreadStart(sendData)); //将线程设为后台运行 
                myThread.IsBackground = true;
                myThread.Start();
                btnSend.Enabled = false;
                btnStop.Enabled = true;
                Flag = true;
            }
            else 
            {
                MessageBox.Show("先开启睡眠监测客户端");
            }
            
            //textBoxSend.Focus();
           // sendData();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Flag = false;
            btnSend.Enabled = true;
  //          buttonListen.Enabled = true;
            btnStop.Enabled = false;
            tcpListener.Stop();
            if (aFile != null) 
            {
                aFile.Close();
                aFile = null;
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void buttonListen_Click(object sender, EventArgs e)
        {

            myThread = new Thread(new ThreadStart(listenFunc)); //将线程设为后台运行 
            myThread.IsBackground = true;
            myThread.Start();
            buttonListen.Enabled = false;
            
           
        }

        private void listenFunc() 
        {
            IPAddress remoteIP;
            if (IPAddress.TryParse(TXIP.Text, out remoteIP) == false)
            {
                MessageBox.Show("远程IP格式不正确");
            }
            IPEndPoint iep = new IPEndPoint(remoteIP, port);
            tcpListener = new TcpListener(iep);
            tcpListener.Start();
           
                try
                {
                        tcpClient = tcpListener.AcceptTcpClient();                 
                }
                catch (Exception E)
                {
                   
                    MessageBox.Show(E.ToString());
                }
 
            
           
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Flag = false;
            if (tcpListener != null) 
            {
                tcpListener.Stop();
               
            }
          
        }
    }
}
